﻿using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace TagField
{
	// TODO: Replace, as needed, "TextField" with some other class derived from Microsoft.SharePoint.WebControls.BaseFieldControl.
	[CLSCompliant(false)]
	[Guid("da5b659c-1962-4b5b-81cb-45a63f11b997")]
	public class TagFieldControl : TextField
	{
		#region Public Properties

		/// <summary>
		/// Gets the separator.
		/// </summary>
		/// <value>The separator.</value>
		public string Separator
		{
			get
			{
				object property = Field.GetCustomProperty("Separator");
				return Field != null && property != null ? property.ToString() : string.Empty;
			}
		}

		/// <summary>
		/// Gets the target.
		/// </summary>
		/// <value>The target.</value>
		public string Target
		{
			get
			{
				object property = Field.GetCustomProperty("Target");
				return Field != null && property != null ? property.ToString() : string.Empty;
			}
		}

		#endregion

		#region Inherited Methods

		/// <summary>
		/// Renders the field for display.
		/// </summary>
		/// <param name="output">The output.</param>
		protected override void RenderFieldForDisplay(HtmlTextWriter output)
		{
			//base.RenderFieldForDisplay(output);
			RenderLink(output);
		}

		#endregion

		#region Auxiliary Methods

		/// <summary>
		/// Renders the link.
		/// </summary>
		/// <param name="output">The output.</param>
		private void RenderLink(HtmlTextWriter output)
		{
			string[] tags = ListItemFieldValue.ToString().Split(Separator[0]);
			for (int i = 0; i < tags.Length; i++)
			{
				string tag = tags[i];
				if (i == 0)
					AddTag(output, tag, true);
				else
					AddTag(output, tag, false);
			}
		}

		/// <summary>
		/// Adds the tag.
		/// </summary>
		/// <param name="output">The output.</param>
		/// <param name="tag">The tag.</param>
		/// <param name="isFirst">if set to <c>true</c> [is first].</param>
		private void AddTag(HtmlTextWriter output, string tag, bool isFirst)
		{
			if (!isFirst)
			{
				Label splitter = new Label();
				splitter.Text = Separator + " ";
				splitter.RenderControl(output);
			}
			HyperLink link = new HyperLink();
			link.Text = tag;
			link.NavigateUrl = GetDestinationUrl(tag);
			link.RenderControl(output);
		}

		/// <summary>
		/// Gets the destination URL.
		/// </summary>
		/// <param name="tag">The tag.</param>
		/// <returns></returns>
		private string GetDestinationUrl(string tag)
		{
			return string.IsNullOrEmpty(Target)
			       	? string.Format("{0}/_layouts/OSSSearchResults.aspx?k={1}", SPContext.Current.Web.Url, tag)
			       	: Target + tag;
		}

		#endregion
	}
}